package org.redmagic.client.location;

import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileLocation extends AbstractLocation {

	private static final Log LOG = LogFactory.getLog(FileLocation.class);
	
	FileLocation(String name, URI uri) {
		super(name, uri);
	}
	
	@Override
	public Properties resolvePlaceholders(Set<String> placeholders) {
		
		Properties resolvedProperties = new Properties();
		Properties cachedProperties = new Properties();
		
		try {
			
			// Load the properties from file
			cachedProperties.load(new FileInputStream(new File(this.getUri())));
			
			// Find the placeholders in the properties
			for (String placeholder : placeholders) {
				String property = cachedProperties.getProperty(placeholder);
				if (property != null) {
					resolvedProperties.put(placeholder, property);
				}
			}
			
		} catch (Exception e) {
			LOG.warn("Unable to load properties from uri: " + this.getUri(), e);
		}
		
		return resolvedProperties;
	}

	@Override
	public void finished(Properties resolvedProperties) {
		// Do nothing
	}

	@Override
	public String toString() {
		return (this.getName() == null ? "FileLocation" : this.getName()) + " [" + this.getUri() + "]";
	}
}
